<template>
    <div class="m-view-formula">
        <div>
        	<input type="file" multiple="false" id="sheetjs-input" accept="xls,xlsx" @change="onchange" />
        </div>

        <ag-grid-vue class="m-agTableContent ag-theme-balham" style="height:300px"
        	:gridOptions="gridOptions" 
        	:columnDefs="columnDefs" 
        	:rowData="rowData">
        </ag-grid-vue>
        
    </div>
</template>

<style lang="less">
.m-view-formula {
    .m-agTable {
        position: absolute;
        left: 0;
        right: 0;
        top: 47px;
        bottom: 0;
    }
}
</style>

<script>
import XLSX from 'xlsx';
import _Api from "@/api";
import localeText from "@/i18n/agGridText";

export default {
    data() {
        return {
            gridOptions: null,
            columnDefs: [],
            rowData: [],
            cols:[]
        };
    },
    components: {

    },
    methods: {
        onchange: function (evt) {
            var files = evt.target.files;
            if (!files || files.length == 0) return;

            var self = this;
            var excelFile = files[0];

            var reader = new FileReader();
            reader.onload = function (e) {
                // 数据预处理
                var binary = "";
                var bytes = new Uint8Array(e.target.result);
                var length = bytes.byteLength;
                for (var i = 0; i < length; i++) {
                    binary += String.fromCharCode(bytes[i]);
                }

                /* 读取 workbook */
                var wb = XLSX.read(binary, {
                    type: 'binary'
                });

                /* 选择第一个sheet */
                var wsname = wb.SheetNames[0];
                var ws = wb.Sheets[wsname];

                /* excel转换json数组,加上{header:1}是普通数组，不写是对象数组 */
                var json = XLSX.utils.sheet_to_json(ws);
            
                self.cols = [];
                self.columnDefs = [];
                for(var key in json[0]){
                    var h = {};
                    h.headerName = key;
                    h.field = key;
                    h.width = 100;
                    self.columnDefs.push(h);

                    if(key.indexOf('-') > -1){
                        self.cols.push(key.split('-')[1]);
                    }
                }
                
                self.rowData = json;
            };

            reader.readAsArrayBuffer(excelFile);
        },
        importToRdb(tbName, primaryKey){
            var that = this;
            var excelData = {};
            excelData.creator = this.$global.user.loginName;
            excelData.createId = this.$global.user.username;
            excelData.primaryKey = primaryKey;
            excelData.tableName = tbName;
            excelData.cols = this.cols;

            if(this.rowData.length > 0){
                var rd = [];
                for(var i = 0; i < this.rowData.length; i++){  //重新设置keyName
                    var row = {};
                    for(var key in this.rowData[0]){
                        if(key.indexOf('-') > -1){
                            var newKey = key.split('-')[1];
                            var value = this.rowData[i][key];
                            if(!value) value = '';
                            row[newKey] = value;
                        }
                    }
                    rd.push(row);
                }
                excelData.rows = rd;
                
                _Api.inputExcel(excelData).then(function(response){  //调用接口
                    var data = response.data;
                    console.log(data);
                    if (data.code == "0") {
                        that.$alert(data.info, "消息提示", {
                            confirmButtonText: '确定'}
                        );
                    } else {
                        that.$alert("导入成功！", "消息提示", {
                            confirmButtonText: '确定'}
                        );
                        that.rowData = [];
                    }
                });
            }
            else{
                 that.$alert("无可导入数据！", "消息提示", {
                    confirmButtonText: '确定'}
                );
            }
        }
    },
    beforeMount() {
        console.log(this.$global.user);
        this.gridOptions = {
            localeText: localeText,
            enableColResize: true,
            context: {
                componentParent: this
            }
        }
    },
    mounted() {
        this.gridOptions.api.sizeColumnsToFit();
    }
};
</script>